<script setup>
import { Message, MessageBox } from 'element-ui';
import { merge, forEach } from 'lodash-es';
import { getToken } from '@/utils/auth';
import { useRequest } from '@/hooks/requestHooks.js';
import { useGlobalState } from '@/store/globalState.js';
import {
  provinceList,
  citysList,
  getListPagination,
  getListStatistics,
  addEnterprise,
  getEnterpriseIItem,
  editEnterprise,
  deleteEnterprise,
} from '@/api/index.js';
import { TableList } from '@/components/MainComponents.js';
import { useResetForm } from '@/hooks/tool.js';
import { useWatch } from '@/hooks/useWatch';
const props = defineProps({
  boxHeight: { type: Number, default: null },
});
const editForm = ref(null);
const parentCode = ref('');
const cityCode = ref('');
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  enterpriseName: '',
});
const editParams = ref({
  enterpriseName: '',
  enterpriseCode: '',
  enterpriseViewId: '',
  enterpriseImage: '',
  province: '',
  city: '',
  county: '',
  lon: '', //经度
  lat: '', //纬度
  address: '', //详细地址
  introduce: '', //介绍
});
const fileLists = ref([]);
const enterpriseImage = ref('');
//获取省数据
const [provinceLists, provinceLoading, provinceRun] = useRequest(provinceList, {
  defaultParams: [],
});
//获取县区数据
const [cityList, cityLoading, cityRun] = useRequest(citysList, {
  defaultParams: [{ parentCode: parentCode.value }],
  manual: true,
});
const [countyList, , countyRun] = useRequest(citysList, {
  defaultParams: [{ parentCode: parentCode.value }],
  manual: true,
});
const [enterpriseLists, , enterpriseRun] = useRequest(getEnterpriseIItem, {
  defaultParams: [],
  manual: true,
  // onSuccess: res => {
  //   fileLists.value = {
  //     name: '',
  //     url:enterpriseImage
  //   }
  // }
});
const [editenterpriseLists, , editenterpriseRun] = useRequest(editEnterprise, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      cancel();
      Message.success('编辑成功');
      queryParams.value.pageNum = 1;
      queryParams.value.pageSize = 10;
      run(queryParams.value);
      run2([]);
    }
  },
});
const [deleteEnterpriseLists, , deleteEnterpriseRun] = useRequest(deleteEnterprise, {
  defaultParams: [],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      Message.success('删除成功');
      queryParams.value.pageNum = 1;
      queryParams.value.pageSize = 10;
      run(queryParams.value);
      run2([]);
    }
  },
});
const provinceChange = val => {
  forEach(provinceLists.value, n => {
    if (n.areaName === val) {
      parentCode.value = n.areaCode;
      const obj = ref({
        parentCode: parentCode.value,
      });
      cityRun({ parentCode: parentCode.value });
    }
  });
};
const citysChange = val => {
  cityList.value.rows.map(m => {
    if (m.areaName === val) {
      cityCode.value = m.areaCode;
    }
  });
  countyRun({ parentCode: cityCode.value });
};
const [res, loading, run] = useRequest(getListPagination, {
  defaultParams: [queryParams.value],
});
const [res2, loading2, run2] = useRequest(getListStatistics, {
  defaultParams: [],
});
const [, , addRun] = useRequest(addEnterprise, {
  defaultParams: [editParams.value],
  manual: true,
  onSuccess: data => {
    if (data.code === 200) {
      cancel();
      Message.success(dialogData.value.title + '成功');
      run(queryParams.value);
      run2([]);
    }
  },
});
const list = ref([
  {
    name: '目标企业数：',
    flag: 'targetNum',
  },
  {
    name: '托管企业数量：',
    flag: 'entrustNum',
  },
  {
    name: '托管单位数量：',
    flag: 'branchOfficeNum',
  },
  {
    name: '托管项目数量：',
    flag: 'projectNum',
  },
]);
const detailsTable = (row, index) => {
  dialogData.value.open = true;
  dialogData.value.title = '详情';
  disabled.value = true;
  enterpriseRun(row.enterpriseCode);
};
const editTable = (row, index) => {
  dialogData.value.open = true;
  dialogData.value.title = '编辑';
  enterpriseRun(row.enterpriseCode);
};
useWatch(enterpriseLists, n => {
  editParams.value = merge(editParams.value, n);
  if (n.enterpriseImage.length > 0) {
    fileLists.value = [
      {
        name: '',
        url: useGlobalState().globalState.fileUrl + n.enterpriseImage,
      },
    ];
  }
});
const deleteTable = (row, index) => {
  MessageBox.confirm('是否删除', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteEnterpriseRun({ enterpriseCode: row.enterpriseCode });
    })
    .catch(() => {});
};
const columObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'enterpriseName',
      label: '企业名称',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'address',
      label: '注册地址',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'branchOfficeNum',
      label: '托管单位数',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'projectNum',
      label: '托管项目数量',
      width: '',
      align: 'center',
    },
    {
      text: true,
      prop: 'contractAmount',
      label: '托管项目合同总金额(万元)',
      width: '',
      align: 'center',
      retain: '2',
    },
    {
      // prop: 'name',
      label: '操作',
      width: '',
      align: 'center',
      operations: [
        {
          type: 'text',
          label: '详情',
          buttonClick: detailsTable,
        },
        {
          type: 'text',
          label: '编辑',
          buttonClick: editTable,
        },
        {
          type: 'text',
          label: '删除',
          buttonClick: deleteTable,
        },
      ],
    },
  ],
});
const pageObj = ref({
  total: res.total,
  page: 1,
  pageSize: 10,
});
const getList = e => {
  queryParams.value.pageNum = e.page;
  queryParams.value.pageSize = e.limit;
  run(queryParams.value);
};
const dialogData = ref({
  open: false,
  title: '',
});
const disabled = ref(false);
const upload = ref({
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: useGlobalState().globalState.serverUrl + '/file/uploadFile',
});
const addEnterpriseButton = () => {
  dialogData.value.open = true;
  dialogData.value.title = '新增';
};
const handleQuery = () => {
  run(queryParams.value);
};
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    enterpriseName: '',
  };
  run(queryParams.value);
};
const handleUploadChange = (file, fileList) => {};
// 超出限制上传数量回调
const handleExceed = () => {
  Message.warning('当前限制最大上传数量：1 ,上传新的文件之前请先删除原文件！');
};
const beforeAvatarUpload = file => {
  console.log(file, 'file====');
  let types = ['image/gif', 'image/jpg', 'image/png', 'image/jpeg'];
  const isImage = types.includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isImage) {
    Message.error('上传头像图片只能是 JPG、GIF、PNG 格式!');
  }
  if (!isLt2M) {
    Message.error('上传头像图片大小不能超过 5MB!');
  }
  return isImage && isLt2M;
};
const handleAvatarSuccess = (response, file, fileList) => {
  enterpriseImage.value = response.data.url;
  editParams.value.enterpriseImage = response.data.url;
  editForm.value.validateField('enterpriseImage');
};
const handleRemove = () => {
  enterpriseImage.value = '';
  editParams.value.enterpriseImage = '';
  editForm.value.validateField('enterpriseImage');
};
const cancel = () => {
  dialogData.value.open = false;
  editParams.value = {
    enterpriseName: '',
    enterpriseViewId: '',
    enterpriseImage: '',
    province: '',
    city: '',
    county: '',
    lon: '', //经度
    lat: '', //纬度
    address: '', //详细地址
    introduce: '', //介绍
  };
  fileLists.value = [];
  disabled.value = false;
  enterpriseImage.value = '';
  useResetForm(editForm);
};
const submitForm = () => {
  if (dialogData.value.title === '新增') {
    editForm.value.validate(valid => {
      if (valid) {
        editParams.value.enterpriseImage = enterpriseImage.value;
        addRun(editParams.value);
      } else {
        return false;
      }
    });
  } else {
    editForm.value.validate(valid => {
      if (valid) {
        if (enterpriseImage.value.length > 0) {
          editParams.value.enterpriseImage = enterpriseImage.value;
        }
        editenterpriseRun(editParams.value);
      }
    });
  }
};
</script>
<template>
  <div class="u-base-fg">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="infoForm u-bb20 u-border-bg u-p20">
      <el-form-item label="企业名称：" prop="enterpriseName">
        <el-input
          class="el-input_search"
          v-model.trim="queryParams.enterpriseName"
          placeholder="请输入"
          clearable
          accordion
          size="small"
          style="width: 372px !important"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button size="small" type="primary" plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="contBox">
      <div class="u-df-spb mb20">
        <div>
          <span class="u-fs16 u-primary u-pr10" v-for="item in list" :key="item.name">
            {{ item.name + (res2?.[item.flag] ?? '--') }}
          </span>
        </div>
        <el-button type="primary" plain size="small" @click="addEnterpriseButton">新增企业</el-button>
      </div>
      <TableList
        v-loading="loading"
        :total="res?.total ?? 0"
        :tableData="res?.rows"
        :columObj="columObj"
        :pageObj="queryParams"
        :height="boxHeight - 310"
        @getList="getList"
      />
    </div>
    <el-dialog :visible.sync="dialogData.open" width="50%" :before-close="cancel" append-to-body>
      <div slot="title" class="dialog-title">
        <span class="tit">
          {{ dialogData.title }}-
          <span class="u-prim-text">企业</span>
        </span>
      </div>
      <el-form
        :model="editParams"
        :inline="true"
        ref="editForm"
        size="small"
        label-width="120px"
        class="editForm"
        :disabled="disabled"
      >
        <el-form-item
          label="企业名称："
          prop="enterpriseName"
          :rules="{ required: true, message: '请输入企业名称', trigger: ['blur', 'change'] }"
        >
          <el-input
            v-filter-input
            style="width: 300px"
            v-model.trim="editParams.enterpriseName"
            placeholder="请输入企业名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item
          label="企业编码："
          prop="enterpriseViewId"
          :rules="
            dialogData.title === '详情'
              ? []
              : [{ required: true, message: '请输入企业编码', trigger: ['blur', 'change'] }]
          "
        >
          <el-input
            v-filter-input
            style="width: 300px"
            v-model.trim="editParams.enterpriseViewId"
            placeholder="请输入企业编码"
            clearable
            size="small"
          />
        </el-form-item>
        <br />
        <el-form-item
          label="企业展示图："
          prop="enterpriseImage"
          :rules="{
            required: true,
            message: '请上传企业展示图',
            trigger: ['blur', 'change'],
          }"
        >
          <el-upload
            v-if="dialogData.title !== '详情'"
            :action="upload.url"
            list-type="picture-card"
            :limit="1"
            name="file"
            :show-file-list="true"
            :headers="upload.headers"
            :on-change="handleUploadChange"
            :before-upload="beforeAvatarUpload"
            :on-exceed="handleExceed"
            :file-list="fileLists"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <img v-else :src="fileLists[0]?.url" style="width: 146px; height: 146px" />
        </el-form-item>
        <br />
        <el-form-item
          label="注册地址："
          :rules="{ required: true, message: '请输入注册地址', trigger: ['blur', 'change'] }"
        >
          <el-form-item prop="province" :rules="{ required: true, message: '请选择省', trigger: 'change' }">
            <el-select
              class="el-input_search"
              v-model="editParams.province"
              placeholder="请选择省"
              clearable
              size="small"
              style="width: 120px !important"
              @change="provinceChange"
            >
              <el-option
                v-for="dict in provinceLists"
                :key="dict.areaCode"
                :label="dict.areaName"
                :value="dict.areaName"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="city" :rules="{ required: true, message: '请选择市', trigger: 'change' }">
            <el-select
              class="el-input_search"
              v-model="editParams.city"
              placeholder="请选择市"
              clearable
              size="small"
              style="width: 120px !important"
              @change="citysChange"
            >
              <el-option
                v-for="dict in cityList?.rows ?? []"
                :key="dict.areaCode"
                :label="dict.areaName"
                :value="dict.areaName"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="county" :rules="{ required: true, message: '请选择县', trigger: 'change' }">
            <el-select
              class="el-input_search"
              v-model="editParams.county"
              placeholder="请选择县"
              clearable
              size="small"
              style="width: 120px !important"
            >
              <el-option
                v-for="dict in countyList?.rows ?? []"
                :key="dict.areaCode"
                :label="dict.areaName"
                :value="dict.areaName"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="lon" :rules="{ required: true, message: '请输入经度', trigger: 'blur' }">
            <el-input
              v-filter-input
              oninput="value=value.replace(/[^0-9.]/g,'')"
              style="width: 130px"
              v-model.trim="editParams.lon"
              placeholder="经度"
              clearable
              size="small"
            />
          </el-form-item>
          <el-form-item prop="lat" :rules="{ required: true, message: '请输入纬度', trigger: 'blur' }">
            <el-input
              v-filter-input
              oninput="value=value.replace(/[^0-9.]/g,'')"
              style="width: 150px"
              v-model.trim="editParams.lat"
              placeholder="纬度"
              clearable
              size="small"
            />
          </el-form-item>
          <br />
          <el-form-item prop="address" :rules="{ required: true, message: '请输入详细地址', trigger: 'blur' }">
            <el-input
              v-filter-input
              style="width: 250px"
              v-model.trim="editParams.address"
              placeholder="请输入详细地址"
              clearable
              size="small"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item
          label="企业介绍："
          prop="introduce"
          :rules="{ required: true, message: '请输入企业介绍', trigger: 'blur' }"
        >
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="editParams.introduce"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="dialogData.title !== '详情'">
        <el-button size="small" @click="cancel" type="primary" plain>取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm('editForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.u-bb20 {
  border-bottom-width: 20px;
  border-bottom-style: solid;
}
.infoForm {
  .el-form-item {
    margin-bottom: 0;
  }
}

.contBox {
  margin-top: 0px;
}

.u-prim-text {
  font-weight: 400;
}

.editForm ::v-deep(.el-textarea__inner) {
  height: 120px;
  width: 750px;
}
.app-dark .editForm ::v-deep(.el-textarea__inner) {
  background: rgba(0, 0, 0, 0.5);
  border: 1px solid #262f48;
}
</style>
